import { LoginResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import http from '@/utils/http'
import { clearToken, setToken } from '@/utils/token'

type LoginParams = { mobile: string; code: string }

export const login = (data: LoginParams): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.post<LoginResponse>('/authorizations', data)

    setToken(res.data.data)
    dispatch({ type: 'login/token', payload: res.data.data })
  }
}

export const getCode = (mobile: string): RootThunkAction => {
  return async () => {
    await http.get(`/sms/codes/${mobile}`)
  }
}

export const logout = (): RootThunkAction => {
  return (dispatch) => {
    clearToken()
    dispatch({ type: 'login/logout' })
  }
}
